package main

import (
	"fmt"
	"time"

	"github.com/gorhill/cronexpr"
)

func main() {

	//define task
	type TASK struct {
		name     string
		expr     *cronexpr.Expression
		nextTime time.Time
	}

	var (
		task01  TASK
		task02  TASK
		taskMap map[string]*TASK
	)

	task01 = TASK{}
	task01.name = "task01"
	task01.expr, _ = cronexpr.Parse("*/1 * * * *")
	task01.nextTime = task01.expr.Next(time.Now())

	task02 = TASK{}
	task02.name = "task02"
	task02.expr, _ = cronexpr.Parse("*/1 * * * *")
	task02.nextTime = task02.expr.Next(time.Now())

	taskMap = make(map[string]*TASK)
	taskMap[task01.name] = &task01
	taskMap[task02.name] = &task02

	// check task whether the task need run, run and change exec time

	for {
		// loop find which is need to run
		for _, task := range taskMap {
			if task.nextTime.Before(time.Now()) || task.nextTime.Equal(time.Now()) {
				go func(task *TASK) {
					fmt.Printf("%s %s run\n", task.name, time.Now().Format("2006-01-02 15:04:05"))
					task.nextTime = task.expr.Next(time.Now())
				}(task)
			}
		}
		time.Sleep(100 * time.Millisecond)
	}
}
